package com.muyu.system.danmo.util;

import cn.hutool.extra.spring.SpringUtil;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
public class OrderNoGenerateUtil {

    private static final String env = SpringUtil.getActiveProfile();


    private static final String ORDER_NO_PREFIX = "cloud:union:pay:orderno:trade:";

    private static final String REFUND_ORDER_NO_PREFIX = "cloud:union:pay:orderno:refund:";


    public static String pay() {
        StringBuilder orderNo = new StringBuilder();
        String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHHmmss"));
        RAtomicLong atomicLong = SpringUtil.getBean(RedissonClient.class).getAtomicLong(ORDER_NO_PREFIX + dateStr);
        if (!atomicLong.isExists()) {
            atomicLong.set(10000);
        }
        long id = atomicLong.incrementAndGet();
        log.info("trade:{},id:{}", dateStr, id);
        if (id > 99999) {
            throw new RuntimeException("生成订单号时间异常");
        }
        if (!"prod".equals(env)) {
            orderNo.append(env);
        }
        orderNo.append(dateStr);
        orderNo.append("T");
        orderNo.append(id);

        return orderNo.toString();
    }


    public static String refund() {
        StringBuilder orderNo = new StringBuilder();
        String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHHmmss"));
        RAtomicLong atomicLong = SpringUtil.getBean(RedissonClient.class).getAtomicLong(REFUND_ORDER_NO_PREFIX + dateStr);
        if (!atomicLong.isExists()) {
            atomicLong.set(10000);
        }
        long id = atomicLong.incrementAndGet();
        log.info("refund:{},id:{}", dateStr, id);
        if (id > 99999) {
            throw new RuntimeException("生成订单号时间异常");
        }
        if ("prod".equals(env)) {
        } else {
            orderNo.append(env);
        }
        orderNo.append(dateStr);
        orderNo.append("R");
        orderNo.append(id);

        return orderNo.toString();

    }
}
